<template>
  <view class="plate-query-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="车牌查询" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
          <template>
            <view></view>
          </template>
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <!-- 筛选条件 -->
          <view class="filter-section">
            <!-- 搜索框 -->
            <view class="filter-item">
              <up-search v-model="searchForm.plateNumber" :clearabled="true" :showAction="true" 
                placeholder="请输入车牌号" @custom="handleSearch" @clear="handleClear">
                <template #action>
                  <up-button type="primary" size="small" @click="handleSearch">搜索</up-button>
                  <up-button type="default" size="small" @click="handleClear" style="margin-left: 5px;">重置</up-button>
                </template>
              </up-search>
            </view>
          </view>
        </up-sticky>
      </template>

      <!-- 列表内容 -->
      <view class="plate-query-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              车牌号：<text class="number">{{ item.plateNumber }}</text>
            </view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">绑定用户：</text>
                <text class="value">{{ item.userName }}</text>
              </view>
              <view class="item">
                <text class="label">是否已认证：</text>
                <text class="value">{{ item.isVerified ? '是' : '否' }}</text>
              </view>
              <view class="item">
                <text class="label">认证时间：</text>
                <text class="value">{{ item.verifyTime || '未认证' }}</text>
              </view>
              <view class="item">
                <text class="label">认证车主姓名：</text>
                <text class="value">{{ item.ownerName || '未认证' }}</text>
              </view>
              <view class="item" v-if="item.verifyImageUrl">
                <text class="label">认证图片：</text>
                <image class="verify-image" :src="item.verifyImageUrl" mode="aspectFit" @click="previewImage(item.verifyImageUrl)"></image>
              </view>
            </view>
            <view class="card-footer">
              <view class="operate">
                <up-button type="primary" text="查看停车记录" class="custom-style" @click.stop="viewParkingRecords(item)"></up-button>
                <up-button type="warning" text="解除认证" class="custom-style" @click.stop="cancelVerify(item)" v-if="item.isVerified"></up-button>
                <up-button type="danger" text="解除绑定" class="custom-style" @click.stop="cancelBinding(item)"></up-button>
                <up-button type="info" text="隐私保护设置" class="custom-style" @click.stop="showPrivacySettings(item)"></up-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>

    <!-- 停车记录弹窗 -->
    <parking-records-modal ref="parkingRecordsModal" v-model:show="showParkingRecordsModal" :recordsList="selectedVehicleRecords" @close="handleParkingRecordsModalClose" />
    
    <!-- 解除认证确认弹窗 -->
    <up-popup v-model:show="showCancelVerifyModal" overlay mode="center" :round="10" closeable closeOnClickOverlay>
      <view class="confirm-modal">
        <view class="modal-title">解除认证确认</view>
        <view class="modal-content">确定要解除该车牌的认证吗？</view>
        <view class="modal-footer">
          <up-button type="default" @click="showCancelVerifyModal = false">取消</up-button>
          <up-button type="warning" @click="confirmCancelVerify">确定</up-button>
        </view>
      </view>
    </up-popup>
    
    <!-- 解除绑定确认弹窗 -->
    <up-popup v-model:show="showCancelBindingModal" overlay mode="center" :round="10" closeable closeOnClickOverlay>
      <view class="confirm-modal">
        <view class="modal-title">解除绑定确认</view>
        <view class="modal-content">确定要解除该车牌的绑定吗？</view>
        <view class="modal-footer">
          <up-button type="default" @click="showCancelBindingModal = false">取消</up-button>
          <up-button type="danger" @click="confirmCancelBinding">确定</up-button>
        </view>
      </view>
    </up-popup>
    
    <!-- 隐私保护设置弹窗 -->
    <up-popup v-model:show="showPrivacySettingsModal" overlay mode="center" :round="10" closeable closeOnClickOverlay>
      <view class="privacy-settings-modal">
        <view class="modal-title">车辆隐私保护设置</view>
        <view class="modal-content">
          <view class="setting-item">
            <text class="setting-label">禁止他人绑定</text>
            <up-radio-group v-model="privacySettings.forbidBinding">
              <up-radio label="是" name="true"></up-radio>
              <up-radio label="否" name="false"></up-radio>
            </up-radio-group>
          </view>
          <view class="setting-item">
            <text class="setting-label">禁止他人查询欠费</text>
            <up-radio-group v-model="privacySettings.forbidDebtQuery">
              <up-radio label="是" name="true"></up-radio>
              <up-radio label="否" name="false"></up-radio>
            </up-radio-group>
          </view>
          <view class="setting-item">
            <text class="setting-label">不推送车入消息给绑定用户</text>
            <up-radio-group v-model="privacySettings.disableEntryNotification">
              <up-radio label="是" name="true"></up-radio>
              <up-radio label="否" name="false"></up-radio>
            </up-radio-group>
          </view>
        </view>
        <view class="modal-footer">
          <up-button type="default" @click="showPrivacySettingsModal = false">取消</up-button>
          <up-button type="primary" @click="savePrivacySettings">保存</up-button>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import ParkingRecordsModal from './components/ParkingRecordsModal.vue';

// 搜索表单
const searchForm = reactive({
  plateNumber: '', // 车牌号
});

// z-paging 组件引用
const paging = ref(null);

// 当前列表数据
const currentList = ref([]);

// 选中车辆的停车记录
const selectedVehicleRecords = ref([]);

// 停车记录弹窗引用
const parkingRecordsModal = ref(null);
const showParkingRecordsModal = ref(false);

// 解除认证弹窗
const showCancelVerifyModal = ref(false);
const currentVehicle = ref(null);

// 解除绑定弹窗
const showCancelBindingModal = ref(false);

// 隐私保护设置弹窗
const showPrivacySettingsModal = ref(false);
const privacySettings = reactive({
  forbidBinding: 'false',
  forbidDebtQuery: 'false',
  disableEntryNotification: 'false'
});

// 处理搜索
const handleSearch = () => {
  if (!searchForm.plateNumber) {
    uni.showToast({
      title: '请输入车牌号',
      icon: 'none'
    });
    return;
  }
  paging.value.reload();
};

// 处理清除
const handleClear = () => {
  searchForm.plateNumber = '';
  currentList.value = [];
};

// 处理返回点击事件
const handleBackClick = () => {
  uni.redirectTo({
    url: '/pages/home/index'
  });
};

// 查看停车记录
const viewParkingRecords = (item) => {
  // 模拟获取车辆停车记录
  selectedVehicleRecords.value = generateMockParkingRecords(item);
  showParkingRecordsModal.value = true;
};

// 处理停车记录弹窗关闭事件
const handleParkingRecordsModalClose = () => {
  console.log('停车记录弹窗已关闭');
};

// 解除认证
const cancelVerify = (item) => {
  currentVehicle.value = item;
  showCancelVerifyModal.value = true;
};

// 确认解除认证
const confirmCancelVerify = () => {
  // 模拟API调用
  uni.showLoading({ title: '处理中...' });
  setTimeout(() => {
    uni.hideLoading();
    uni.showToast({
      title: '解除认证成功',
      icon: 'success'
    });
    showCancelVerifyModal.value = false;
    // 更新列表数据
    if (currentVehicle.value) {
      const index = currentList.value.findIndex(item => item.id === currentVehicle.value.id);
      if (index !== -1) {
        currentList.value[index].isVerified = false;
        currentList.value[index].verifyTime = '';
        currentList.value[index].ownerName = '';
        currentList.value[index].verifyImageUrl = '';
      }
    }
  }, 1000);
};

// 解除绑定
const cancelBinding = (item) => {
  currentVehicle.value = item;
  showCancelBindingModal.value = true;
};

// 确认解除绑定
const confirmCancelBinding = () => {
  // 模拟API调用
  uni.showLoading({ title: '处理中...' });
  setTimeout(() => {
    uni.hideLoading();
    uni.showToast({
      title: '解除绑定成功',
      icon: 'success'
    });
    showCancelBindingModal.value = false;
    // 更新列表数据
    if (currentVehicle.value) {
      const index = currentList.value.findIndex(item => item.id === currentVehicle.value.id);
      if (index !== -1) {
        // 从列表中移除该项
        currentList.value.splice(index, 1);
      }
    }
  }, 1000);
};

// 隐私保护设置
const showPrivacySettings = (item) => {
  currentVehicle.value = item;
  // 重置设置
  privacySettings.forbidBinding = 'false';
  privacySettings.forbidDebtQuery = 'false';
  privacySettings.disableEntryNotification = 'false';
  showPrivacySettingsModal.value = true;
};

// 保存隐私保护设置
const savePrivacySettings = () => {
  // 模拟API调用
  uni.showLoading({ title: '保存中...' });
  setTimeout(() => {
    uni.hideLoading();
    uni.showToast({
      title: '设置保存成功',
      icon: 'success'
    });
    showPrivacySettingsModal.value = false;
  }, 1000);
};

// 预览图片
const previewImage = (url) => {
  uni.previewImage({
    urls: [url],
    current: url
  });
};

// 生成模拟停车记录数据
const generateMockParkingRecords = (vehicle) => {
  const count = Math.floor(Math.random() * 5) + 1; // 1-5条记录
  return Array.from({ length: count }, (_, i) => ({
    parkingId: `${Math.floor(Math.random() * 1000000)}`,
    parkingLocation: `${['南海区', '顺德区', '禅城区', '三水区'][Math.floor(Math.random() * 4)]}停车场${Math.floor(Math.random() * 100) + 1}号`,
    startTime: `2023-${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 28) + 1} ${Math.floor(Math.random() * 24).toString().padStart(2, '0')}:${Math.floor(Math.random() * 60).toString().padStart(2, '0')}`,
    endTime: `2023-${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 28) + 1} ${Math.floor(Math.random() * 24).toString().padStart(2, '0')}:${Math.floor(Math.random() * 60).toString().padStart(2, '0')}`,
    fee: (Math.random() * 20).toFixed(2),
    isPaid: Math.random() > 0.5
  }));
};

// 查询列表数据
const queryList = async (pageNo, pageSize) => {
  try {
    // 处理搜索参数
    const params = {
      pageNo,
      pageSize,
      plateNumber: searchForm.plateNumber
    };
    
    // 模拟API调用
    // 实际项目中应替换为真实API
    // const result = await getPlateQueryList(params);
    // const data = result.data;
    
    // 模拟数据
    const mockData = {
      total: 100,
      list: Array.from({ length: 10 }, (_, i) => ({
        id: `${pageNo}-${i}`,
        plateNumber: searchForm.plateNumber || `粤${String.fromCharCode(65 + Math.floor(Math.random() * 26))}${Math.floor(Math.random() * 10000).toString().padStart(5, '0')}`,
        userName: `用户${Math.floor(Math.random() * 1000) + 1}`,
        isVerified: Math.random() > 0.3,
        verifyTime: Math.random() > 0.3 ? `2023-${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 28) + 1}` : '',
        ownerName: Math.random() > 0.3 ? `车主${Math.floor(Math.random() * 100) + 1}` : '',
        verifyImageUrl: Math.random() > 0.3 ? 'https://picsum.photos/200/300' : ''
      }))
    };
    
    // 通知z-paging组件数据加载完成
    paging.value.complete(mockData.list);
  } catch (error) {
    console.error('获取车牌查询列表数据失败:', error);
    paging.value.complete(false);
  }
};

onMounted(() => {
  // 初始页面不自动加载数据，等待用户搜索
});
</script>

<style lang="scss" scoped>
.plate-query-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  
  .filter-section {
    margin-bottom: 10px;
    
    .filter-item {
      margin-bottom: 10px;
    }
  }
}

.plate-query-list {
  padding: 20px;
  
  .list-item-card {
    .card-content-box {
      .content {
        .item {
          .verify-image {
            width: 80px;
            height: 80px;
            border-radius: 4px;
          }
        }
      }
      
      .card-footer {
        display: flex;
        justify-content: flex-end;
        
        .operate {
          display: flex;
          flex-wrap: wrap;
          gap: 10px;
          
          .custom-style {
            font-size: 12px;
            padding: 5px 10px;
          }
        }
      }
    }
  }
}

.confirm-modal {
  width: 80vw;
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  
  .modal-title {
    font-size: 16px;
    font-weight: bold;
    text-align: center;
    margin-bottom: 20px;
  }
  
  .modal-content {
    text-align: center;
    margin-bottom: 20px;
  }
  
  .modal-footer {
    display: flex;
    justify-content: space-around;
  }
}

.privacy-settings-modal {
  width: 80vw;
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  
  .modal-title {
    font-size: 16px;
    font-weight: bold;
    text-align: center;
    margin-bottom: 20px;
  }
  
  .modal-content {
    margin-bottom: 20px;
    
    .setting-item {
      margin-bottom: 15px;
      
      .setting-label {
        display: block;
        margin-bottom: 10px;
        font-weight: bold;
      }
    }
  }
  
  .modal-footer {
    display: flex;
    justify-content: space-around;
  }
}
</style>